package top.infopub.mgr.mkt.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.dto.mkt.AfterSummaryDto;
import top.infopub.enums.mkt.ProProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.cnst.FlowTemplateEnum;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.flow.service.WsFlowProcessService;
import top.infopub.mgr.mkt.dao.*;
import top.infopub.mgr.mkt.domain.AfterSummaryDomain;
import top.infopub.mgr.mkt.jsonvo.AfterSummaryJsonVo;
import top.infopub.mgr.mkt.service.AfterSummaryService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.mgr.mkt.vo.AfterSummaryVo;
import top.infopub.model.mkt.*;
import top.infopub.security.vo.AuthorizationVO;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class AfterSummaryServiceImpl extends GenericServiceImpl<AfterSummary, String> implements
		AfterSummaryService {

	@Autowired
	private AfterSummaryDao afterSummaryDao;

	@Autowired
	private AfterSummaryBidDao afterSummaryBidDao;

	@Autowired
	private AfterSummaryCoopDao afterSummaryCoopDao;

	@Autowired
	private AfterSummaryOurDao afterSummaryOurDao;

	@Autowired
	private AfterSummaryRankDao afterSummaryRankDao;

	@Autowired
	private AfterSummaryAttDao afterSummaryAttDao;

	@Autowired
    private ProjectAttachmentDao projectAttachmentDao;

	@Autowired
    private ProjectInfoDao projectInfoDao;

	@Autowired
    private WsFlowProcessService wsFlowProcess;

	@Autowired
    private SetupProService setupProService;

	@Autowired
    private ProProcessManageService proProcessManageService;

	@Autowired
    private BidOpenRecordDao bidOpenRecordDao;

	@Autowired
    private OAFlowService oaFlowService;

	@Override
	public GenericDao<AfterSummary, String> getDao() {
		return afterSummaryDao;
	}

    @Override
    public Page<AfterSummaryDomain> selectByDomainWhere(Page<AfterSummaryDomain> page,
                                                        AfterSummaryVo afterSummaryVo) throws ParseException {

        //处理时间范围
        if (!StringUtils.isEmpty(afterSummaryVo.getDates()))
        {
            String[] splitTime = afterSummaryVo.getDates().split("~");
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            afterSummaryVo.setStartDate(format.parse(splitTime[0]));
            afterSummaryVo.setEndDate(format.parse(splitTime[1]));
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<AfterSummaryDomain>)afterSummaryDao.selectByDomainWhere(afterSummaryVo);
    }

    @Override
    public Page<AfterSummaryDomain> selectMyCheckByDomainWhere(Page<AfterSummaryDomain> page,
                                                               AfterSummaryVo afterSummaryVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<AfterSummaryDomain>)afterSummaryDao.selectMyCheckByDomainWhere(afterSummaryVo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAfterSummary(AfterSummary afterSummary,
                                 List<AfterSummaryBid> afterSummaryBids,
                                 List<AfterSummaryCoop> afterSummaryCoops,
                                 List<AfterSummaryOur> afterSummaryOurs,
                                 List<AfterSummaryRank> afterSummaryRanks,
                                 List<AfterSummaryAtt> afterSummaryAtts) {

        afterSummaryDao.insertById(afterSummary);

        if(CollectionUtils.isNotEmpty(afterSummaryBids)){
            afterSummaryBidDao.insertByBatch(afterSummaryBids);
        }

        if(CollectionUtils.isNotEmpty(afterSummaryCoops)){
            afterSummaryCoopDao.insertByBatch(afterSummaryCoops);
        }

        if(CollectionUtils.isNotEmpty(afterSummaryOurs)){
            afterSummaryOurDao.insertByBatch(afterSummaryOurs);
        }

        if(CollectionUtils.isNotEmpty(afterSummaryRanks)){
            afterSummaryRankDao.insertByBatch(afterSummaryRanks);
        }

        if(CollectionUtils.isNotEmpty(afterSummaryAtts)){
            afterSummaryAttDao.insertByBatch(afterSummaryAtts);
        }

        // 注意 这里根据不同的业务分支判断条件 获得不同enum
        FlowTemplateEnum templateEnum = FlowTemplateEnum.MKT_AFTER_SUMMARY;
        // 处理工作流数据
        wsFlowProcess.launch(templateEnum, afterSummary.getId(), afterSummary.getProcessId(), null);

    }

    @Override
    public AfterSummaryVo queryById(String id) {
        return afterSummaryDao.queryById(id);
    }

    @Override
    public AfterSummaryJsonVo queryDetailById(String id) {
	    AfterSummaryJsonVo afterSummJson = new AfterSummaryJsonVo();
	    //基础信息
	    AfterSummaryDto afterSummDto = afterSummaryDao.queryDetailById(id);
        afterSummJson.setInfo(afterSummDto);

//	    开标记录及排名
        List<AfterSummaryRank> afterSummRankList = afterSummaryRankDao.selectByAfterSummaryId(afterSummDto.getBidOpenResId());
        afterSummJson.setAfterSummRankList(afterSummRankList);
//        List<BidOpenRecord> bidOpenRecords = bidOpenRecordDao.selectByBidResId(afterSummDto.getBidOpenResId());
//        afterSummJson.setBidOpenRecords(bidOpenRecords);

        //中标单位报价
        List<AfterSummaryBid> afterSummBidList = afterSummaryBidDao.selectByAfterSummaryId(afterSummDto.getBidOpenResId());
        afterSummJson.setAfterSummBidList(afterSummBidList);

        //附件信息
        List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(afterSummDto.getProCode(), ProjectFileTypeEnum.FILE_TYPE28.getCode(), null);
        afterSummJson.setFileAtt(setupProService.fileAttaListToArray(projectAttaList));
        return afterSummJson;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RspVo editDetail(AfterSummary afterSummary, List<ProjectAttachment> attachmentList, AuthorizationVO vo, Integer submitType) {
        //根据pro_code查询项目基础信息
        ProjectInfo tmpProInfo = projectInfoDao.findByProCode(afterSummary.getProCode());
        if (tmpProInfo == null) return RspVo.getFailureResponse(400, "项目基础信息不存在");
        AfterSummary tmpAs = afterSummaryDao.selectByPrimaryKey(afterSummary.getId());
        if (tmpAs == null) return RspVo.getFailureResponse(400, "标后总结信息不存在");
        //判断审批状态
        if (StringUtils.isNotBlank(tmpAs.getProcessStatus())
                && (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), tmpAs.getProcessStatus())
                || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), tmpAs.getProcessStatus()))) {
            return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
        }

        //更新开标结果信息
        afterSummary.setUptBy(vo.getId());
        afterSummary.setUptTime(new Date());
        afterSummaryDao.updateByIdSelective(afterSummary);

        //更新附件信息
        projectAttachmentDao.deleteByWhere(afterSummary.getProCode(), ProjectFileTypeEnum.FILE_TYPE28.getCode(), null);
        if (attachmentList != null && attachmentList.size() > 0) {
            projectAttachmentDao.insertBatch(attachmentList);
        }

        if (submitType == 1) {
            //处理OA待办信息
            if (StringUtils.isNotBlank(tmpAs.getOaId())) {
                oaFlowService.finishOA(tmpAs.getOaId());
            }
            String detailJson = JSON.toJSONString(queryDetailById(afterSummary.getId()));
            proProcessManageService.sendProcess(ProProcessDetailTypeEnum.PRO_NODE_TYPE11, detailJson, afterSummary.getId(), afterSummary.getProCode(), vo);
        }
        return RspVo.getSuccessResponse();
    }
}
